package xyz.quanguanjia.masterboy;

import android.view.View;
import android.widget.ImageView;

import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;

import xyz.quanguanjia.masterboy.base.BaseFragment;

public class TabLayoutTabListener implements TabLayout.OnTabSelectedListener {

    private final ArrayList<TabIdModel> mTabIdModels;

    public TabLayoutTabListener(ArrayList<TabIdModel> tabIdModels){
        this.mTabIdModels = tabIdModels;
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        View view = tab.getCustomView();
        if (null != view) {
            int position = tab.getPosition();
            ImageView iconImageView = view.findViewById(R.id.tab_icon);
            iconImageView.setImageResource(mTabIdModels.get(position).highlightResourceId);
        }
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
        View view = tab.getCustomView();
        if (null != view) {
            int position = tab.getPosition();
            ImageView iconImageView = view.findViewById(R.id.tab_icon);
            iconImageView.setImageResource(mTabIdModels.get(position).normalResourceId);
        }
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

    public static class TabIdModel {
        Integer normalResourceId;
        Integer highlightResourceId;

        public static ArrayList<TabIdModel> idsWithFragments(ArrayList<BaseFragment> fragments) {
            ArrayList<TabLayoutTabListener.TabIdModel> ids = new ArrayList<>();
            for (int i = 0; i < fragments.size(); i++) {
                BaseFragment fragment = fragments.get(i);
                int hResId = fragment.fragmentIconId(BaseFragment.HIGHLIGHT);
                int nResId = fragment.fragmentIconId(BaseFragment.NORMAL);
                TabLayoutTabListener.TabIdModel item = new TabLayoutTabListener.TabIdModel();
                item.highlightResourceId = hResId;
                item.normalResourceId = nResId;
                ids.add(item);
            }
            return ids;
        }
    }
}
